package net.esj.basic.plugins.richtext;

import java.io.File;
import java.util.Calendar;

import net.esj.basic.core.engine.tools.rule.FileRule;
import net.esj.basic.utils.StringUtils;

import org.apache.commons.lang.RandomStringUtils;

public class RichTextFileRule implements FileRule {
	
	private String rootPath;
	
	public RichTextFileRule(String rootPath) {
		super();
		if(rootPath.endsWith(File.separator)){
			rootPath = rootPath.substring(0, rootPath.length()-1);
		}
		this.rootPath = rootPath;
	}

	@Override
	public String getAbsoluteParentPath() {
		return getRootPath()+getParentPath();
	}

	@Override
	public String getAbsolutePath() {
		return getRootPath()+getPath();
	}

	/**
	 * 随机4位+当前时间转N36 不包含后缀
	 */
	@Override
	public String getFileName() {
		String name = StringUtils.longToN36(System.currentTimeMillis());
		return RandomStringUtils.random(4, StringUtils.getN36Chars()) + name;
	}

	@Override
	public String getParentPath() {
		Calendar cal = Calendar.getInstance();
		StringBuilder sb = new StringBuilder();
		sb.append(File.separatorChar).append(cal.get(Calendar.YEAR)).append(File.separatorChar)
		.append(cal.get(Calendar.MONTH+1)).append(File.separatorChar).append(cal.get(Calendar.DAY_OF_MONTH))
		.append(File.separatorChar);
		return sb.toString();
	}

	@Override
	public String getPath() {
		return getParentPath()+getFileName()+"."+getSuffix();
	}

	@Override
	public String getRootPath() {
		return rootPath;
	}

	@Override
	public String getSuffix() {
		return "txt";
	}

	@Override
	public void mkDirs() {
		File file = new File(getAbsoluteParentPath());
		file.mkdirs();
	}

}
